package com.blog.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.service.RedisService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Copyright (C), 2022
 * Author: 苏大大
 * Date: 2022-04-23 16:44
 * FileName: RedisServiceImpl
 * Description:
 */
@Service
public class RedisServiceImpl  implements RedisService {
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<?> getCache(Class aClass,String ListName,BaseMapper mapper) {

        if(redisTemplate.opsForValue().get(ListName)!=null){
            String a=redisTemplate.opsForValue().get(ListName).toString();
            List<?> list=(List<?>) JSON.parseArray(a,aClass);
            return list;
        }
        List<?> list=mapper.selectList(null);
        if(list!=null){
            //异常设备的json数组,把list转换为json形式数组
            JSONArray jsonArray= JSONObject.parseArray(JSONObject.toJSONString(list));
            //将json形式数组装换为string类型
            String json= jsonArray.toJSONString();
            //将需要缓存的数据缓存入redis
            redisTemplate.opsForValue().set(ListName,json);
        }
        String a=redisTemplate.opsForValue().get(ListName).toString();
        List<?> List=(List<?>) JSON.parseArray(a,aClass);

        return List;
    }
}
